<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原文件名" prop="originalName">
        <el-input
          v-model="queryParams.originalName"
          placeholder="请输入原文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
          v-hasPermi="['system:fileinfo:upload']"
        >上传文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fileinfo:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件ID" align="center" prop="fileId" />
      <el-table-column label="文件名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="原文件名称" align="center" prop="originalName" :show-overflow-tooltip="true" />
      <el-table-column label="文件大小" align="center" prop="size">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.size) }}
        </template>
      </el-table-column>
      <el-table-column label="文件类型" align="center" prop="type" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
            v-hasPermi="['system:fileinfo:preview']"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['system:fileinfo:download']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fileinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 文件上传对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar"
        :auto-upload="false"
        drag
        :on-change="handleFileChange"
        :on-exceed="handleExceed"
        :file-list="upload.fileList"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            提示：仅允许导入jpg、jpeg、png、gif、bmp、pdf、doc、docx、xls、xlsx、ppt、pptx、txt、zip、rar格式文件！
          </div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="800px" append-to-body>
      <div class="file-preview">
        <div v-if="isImage(preview.file)" class="image-preview">
          <img :src="preview.url" style="max-width: 100%; max-height: 600px;" />
        </div>
        <div v-else-if="isPdf(preview.file)" class="pdf-preview">
          <iframe :src="preview.url" width="100%" height="600px"></iframe>
        </div>
        <div v-else class="file-info">
          <p>文件名称：{{ preview.file.originalName }}</p>
          <p>文件大小：{{ formatFileSize(preview.file.size) }}</p>
          <p>文件类型：{{ preview.file.type }}</p>
          <el-button type="primary" @click="handleDownload(preview.file)">下载文件</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFileInfo, delFileInfo, uploadFileInfo } from "@/api/system/fileinfo";
import { downloadFileByPath } from "@/utils/filedownload";

export default {
  name: "SysFileInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      fileInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        originalName: null
      },
      // 文件上传参数
      upload: {
        // 是否显示弹出层（文件上传）
        open: false,
        // 弹出层标题（文件上传）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 文件上传列表
        fileList: []
      },
      // 文件预览参数
      preview: {
        open: false,
        title: "",
        file: {},
        url: ""
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listFileInfo(this.queryParams).then(response => {
        this.fileInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 文件上传按钮操作 */
    handleUpload() {
      this.upload.title = "文件上传";
      this.upload.open = true;
    },
    /** 文件预览操作 */
    handlePreview(row) {
      this.preview.file = row;
      this.preview.title = "文件预览 - " + row.originalName;
      // 后端返回的URL已经包含/profile前缀，直接使用即可
      this.preview.url = process.env.VUE_APP_BASE_API + row.url;
      this.preview.open = true;
    },
    /** 文件下载操作 */
    handleDownload(row) {
      // 使用若依框架提供的下载方法，添加API前缀
      downloadFileByPath(process.env.VUE_APP_BASE_API + "/system/fileinfo/download/" + row.fileId, row.originalName);
    },
    /** 提交上传文件 */
    submitFileForm() {
      if (this.upload.fileList.length === 0) {
        this.$message.error("请选择要上传的文件");
        return;
      }

      // 创建FormData对象
      const formData = new FormData();
      formData.append("file", this.upload.fileList[0].raw);

      uploadFileInfo(formData).then(response => {
        this.$modal.msgSuccess("上传成功");
        this.upload.open = false;
        this.getList();
      }).catch(() => {
        this.$modal.msgError("上传失败");
      });
    },
    /** 文件上传处理 */
    handleFileChange(file, fileList) {
      this.upload.fileList = fileList;
    },
    /** 文件上传超出限制 */
    handleExceed() {
      this.$message.warning("只能上传一个文件");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除文件编号为"' + fileIds + '"的数据项？').then(function () {
        return delFileInfo(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size) return '0B';
      const units = ['B', 'KB', 'MB', 'GB'];
      let unitIndex = 0;
      let fileSize = size;
      while (fileSize >= 1024 && unitIndex < units.length - 1) {
        fileSize /= 1024;
        unitIndex++;
      }
      return fileSize.toFixed(2) + units[unitIndex];
    },
    /** 判断是否为图片 */
    isImage(file) {
      // 检查文件类型是否存在
      if (!file || !file.type) return false;
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      return imageTypes.includes(file.type.toLowerCase());
    },
    /** 判断是否为PDF */
    isPdf(file) {
      // 检查文件类型是否存在
      if (!file || !file.type) return false;
      return file.type.toLowerCase() === 'pdf';
    }
  }
};
</script>

<style scoped>
.file-preview {
  text-align: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 600px;
}

.file-info {
  padding: 20px;
  text-align: left;
}

.file-info p {
  margin: 10px 0;
}
</style>
